<template>
  <div>
    <el-form ref="editForm" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <div class="anthor">
        <div class="anthor-info">
          <div id="module1">
            <div class="anthor-info-head"><i class="el-icon-document" /><span>基本信息</span></div>
            <div class="anthor-info-body">
              <el-row :gutter="40">
                <el-col :span="8">
                  <el-form-item label="规则名称" required prop="name">
                    <el-input v-model="formItem.name" placeholder="请输入规则名称" :maxlength="255" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="执行部门" required prop="orgCode">
                    <treeselect
                      v-model="formItem.orgCode"
                      :multiple="false"
                      :options="availableOganizations"
                      placeholder="请选择执行部门"
                      @select="selcetOrg"
                      @input="inputOrg"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="职能分组" required prop="inspectionType" title="当前部门下的职能分组">
                    <el-select v-model="formItem.inspectionType" class="select_input" placeholder="请选择部门下的职能" :disabled="!formItem.orgCode">
                      <el-option v-for="(item) in inspectionTypes" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="起始时间" required prop="startDateTime">
                    <el-date-picker
                      v-model="formItem.startDateTime"
                      type="datetime"
                      placeholder="选择日期时间"
                      align="right"
                      :picker-options="pickerOptions"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="结束时间" required prop="endDateTime">
                    <el-date-picker
                      v-model="formItem.endDateTime"
                      type="datetime"
                      placeholder="选择日期时间"
                      align="right"
                      :picker-options="pickerOptions"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="时长（时）" required prop="duration">
                    <el-input-number v-model="formItem.duration" :precision="2" :step="1" :max="1000000000" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="规则状态">
                    <el-radio-group v-model="formItem.status">
                      <el-radio label="start">启用</el-radio>
                      <el-radio label="stop">停用</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                  <el-form-item label="当前版本" title="自动生成">
                    <el-input v-model="formItem.version" disabled />
                  </el-form-item>
                </el-col> -->
              </el-row>
            </div>
          </div>

          <div id="module2">
            <div class="anthor-info-head">
              <i class="el-icon-document" /><span>巡检内容</span>
              <div>
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleSelectAssets">增加</el-button>
                <el-button type="primary" size="mini" icon="el-icon-delete" @click="handleRemove">移除</el-button>
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEdit">编辑</el-button>
              </div>
            </div>
            <div class="anthor-info-body">
              <PageableTable
                :loading="false"
                :data="formItem.inspectionProject"
                :table-height="500"
                :disable-pageable="true"
                :multiple-selected="true"
                class="fixed-table-table"
                @selection-change="tableSelection"
              >
                <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
                  <template slot-scope="scope">
                    <column-render :render="column.render" :row="scope.row" :column="column" />
                  </template>
                </el-table-column>
                <el-table-column label="巡检对象" prop="projectConcrete">
                  <template slot-scope="{row}">
                    <div v-if="Array.isArray(row.projectConcrete)">
                      <p v-for="(adr, index) in row.projectConcrete" :key="index">{{ adr.concreteName }}</p>
                    </div>
                    <span v-else>{{ row.address }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="巡检项" prop="inspectionItem">
                  <template slot-scope="{row}">
                    <div v-if="Array.isArray(row.inspectionItem)">
                      <p v-for="(adr, index) in row.inspectionItem" :key="index">{{ adr.name }}</p>
                    </div>
                    <span v-else>{{ row.address }}</span>
                  </template>
                </el-table-column>

              </PageableTable>
            </div>
          </div>

          <div id="module3">
            <div class="anthor-info-head"><i class="el-icon-document" /><span>巡检时间</span></div>
            <div class="anthor-info-body">
              <el-row>
                <Cron :value="formItem.cronTime" :second-show="false" @input="cronChange" />
              </el-row>
            </div>
          </div>
          <anchor key="el-dialog__body" :xleft="1" :ytop="10" container=".el-dialog__body" :title-list="anchorList" />
        </div>
      </div>
    </el-form>
    <FormDialog custom-class="second-dialog-height" title="添加巡检对象" :show="dialogFormVisible" :append-to-body="true" width="70%" @on-ok="ok" @on-cancel="cancel">
      <editProjectFormVue v-if="dialogFormVisible" ref="editProjectForm" :init-data="initProjectData" @saveData="saveData" />
    </FormDialog>
  </div>
</template>

<script>
import { list } from '@neu/dcom-ui/api/functional'
import FormDialog from '@neu/biz-core/components/FormDialog'
import treeselect from '@neu/biz-core/components/TreeSelect'
import { create, update, detail } from '@neu/dcom-ui/api/inspectionRule'
import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'
import * as organizations from '@neu/auth-ui/api/organization'
import Cron from '@neu/biz-core/components/Cron'
import PageableTable from '@neu/biz-core/components/PageableTable'
import Anchor from '@neu/biz-core/components/Anchor/index'
import editProjectFormVue from './editProjectForm.vue'
import { formatDate } from '@neu/biz-core/utils/utils'

// 定义一个表单原始项
const formItem = {
  name: '',
  type: '',
  orgCode: null,
  // 部门名称
  orgName: '',
  // 规则编号
  code: '',
  // 规则状态
  status: 'stop',
  // 起始时间
  startDateTime: '',
  // 结束时间
  endDateTime: '',
  // 创建人编码
  usercode: '',
  // 创建人名称
  username: '',
  // 巡检类型：暖通、电气、高压
  inspectionType: '',
  // 版本号
  version: '',
  // 巡检内容
  inspectionProject: [],
  // 巡检时间
  cronTime: '',
  // 巡检时长
  duration: 1
}
export default {
  name: 'InspectionRuleEdit',
  components: {
    Cron,
    PageableTable,
    Anchor,
    treeselect,
    FormDialog,
    editProjectFormVue
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      /** 巡检对象类型 */
      projectTypes: [],
      anchorList: [ // 锚点列表
        { id: 'module1', label: '基本信息' },
        { id: 'module2', label: '巡检内容' },
        { id: 'module3', label: '巡检时间' }
      ],
      dialogFormVisible: false,
      availableOganizations: [],
      inspectionTypes: [],
      // { 'code': 'number', 'text': '防火' }, { 'code': 'string', 'text': '高压' }],
      showCronBox: false,
      /** 启用状态 */
      status: [{ value: 'active', label: '启用' }, { value: 'notActive', label: '未启用' }],
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      initProjectData: {
        id: 0,
        /** 巡检对象类型 */
        projectType: 'asset',
        // 位置编码/系统编码
        locationCode: null,
        // 类型编码
        typeCode: null,
        // 巡检对象
        projectConcrete: [],
        // 巡检项
        inspectionItem: []
      },
      // 表单验证规则
      rules: {
        status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'change' }],
        orgCode: [{ required: true, message: '部门不能为空', trigger: 'change' }],
        inspectionType: [{ required: true, message: '巡检类型不能为空', trigger: 'change' }],
        startDateTime: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
        endDateTime: [{ required: true, message: '结束时间不能为空', trigger: 'change' }],
        duration: [{ required: true, message: '持续时间不能为空', trigger: 'change' }]
      },
      modal: true,
      insideColumns: [
        { title: '巡检对象类型', key: 'projectType', display: true, render: (h, params) => {
          const projectTypeDisplay = this.projectTypes.filter(t => {
            return t.code === params.row.projectType
          })
          const projectTypeDisplayDesc = projectTypeDisplay.length === 1 ? projectTypeDisplay[0].text : params.row.projectType
          return h('span', projectTypeDisplayDesc)
        }
        },
        { title: '规则系统/位置', key: 'locationName', display: true },
        { title: '类型', key: 'typeName', display: true }
        // { title: '资产', key: 'assets', display: true },
        // { title: '巡检项', key: 'items', display: true }
      ],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      removeData: []
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  created() {
    findByDictionaryType('projectType').then(response => {
      this.projectTypes = response.data
    })
    organizations.tree().then(response => {
      this.availableOganizations = [response.data]
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            if (this.formItem.cronTime[0] === '*') {
              return this.$message({
                showClose: true,
                message: "巡检时间设置错误，'秒' 位置不可以是 '*' ",
                type: 'error'
              })
            }
            if (formatDate(this.formItem.startDateTime) > formatDate(this.formItem.endDateTime)) {
              return this.$message({
                showClose: true,
                message: '巡检开始时间不能大于巡检结束时间',
                type: 'error'
              })
            }
            if (this.formItem.inspectionProject.length === 0) {
              return this.$message({
                showClose: true,
                message: '巡检内容不能为空',
                type: 'error'
              })
            }
            if (this.formItem.inspectionProject && this.formItem.inspectionProject.length > 0) {
              this.formItem.inspectionProject.forEach(item => {
                if (item.id && isNaN(item.id) && item.id.indexOf('project') !== -1) {
                  item.id = null
                }
              })
            }
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.editForm.resetFields()
    },
    ok() {
      this.$refs.editProjectForm.save()
    },
    saveData(data) {
      if (data) {
        this.formItem.inspectionProject = this.formItem.inspectionProject.filter(t => {
          return t.id !== data.id
        })
        this.formItem.inspectionProject.push(data)
        this.dialogFormVisible = false
      }
    },
    cancel() {
      this.$refs.editProjectForm.reset()
      this.dialogFormVisible = false

      // this.cronChange('')
    },
    cronChange(v) {
      this.formItem.cronTime = v
    },
    handleSelectAssets() {
      this.initProjectData = {
        id: 'project' + this.formItem.inspectionProject.length,
        /** 巡检对象类型 */
        projectType: 'asset',
        // 位置编码/系统编码
        locationCode: null,
        // 类型编码
        typeCode: null,
        // 巡检对象
        projectConcrete: [],
        // 巡检项
        inspectionItem: [],
        // 巡检对象code集合
        projectConcreteCodes: []
      }
      // this.formItem.inspectionProject.push(this.initProjectData)
      this.dialogFormVisible = true
    },
    handleRemove() {
      if (this.removeData.length === 0) {
        return this.$message({
          showClose: true,
          message: '请至少选择一项巡检内容进行移除操作',
          type: 'error'
        })
      }
      this.formItem.inspectionProject = this.formItem.inspectionProject.filter(t => {
        return !this.removeData.includes(t.id)
      })
    },
    handleEdit() {
      if (this.removeData.length !== 1) {
        return this.$message({
          showClose: true,
          message: '请选择巡检内容进行编辑',
          type: 'error'
        })
      }
      const objArray = this.formItem.inspectionProject.filter(t => {
        return this.removeData.includes(t.id)
      })
      this.initProjectData = objArray[0]
      this.initProjectData['projectConcreteCodes'] = objArray[0].projectConcrete.map(project => project.concreteCode)
      this.dialogFormVisible = true
    },
    tableSelection(sel) {
      this.removeData = sel.map(a => a.id)
    },
    /** 组织机构赋值 */
    selcetOrg(value) {
      this.formItem.orgName = value.title
    },
    inputOrg(value) {
      const obj = this.formItem.inspectionType
      this.formItem.inspectionType = ''
      // if (this.isUpdateInit) {
      //   this.formItem.userId = ''
      //   this.formItem.userName = ''
      // }
      // this.isUpdateInit = true
      if (value === undefined) {
        this.formItem.orgName = ''
        this.inspectionTypes = []
      } else {
        const params = {
          's_orgCode': this.formItem.orgCode
        }
        list(params).then(response => {
          this.inspectionTypes = response.data
          this.formItem.inspectionType = Number(obj) === 0 ? '' : Number(obj)
        })
      }
    }
  }
}
</script>

